<!-- eslint-disable @typescript-eslint/ban-ts-comment -->
<script lang="tsx" setup>
import { ref, toRefs } from 'vue';
import { NButton, NTooltip, useDialog, useMessage } from 'naive-ui';
import { clean, getPageList } from '@/service/api/log/operLog';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { useDict } from '@/utils/dict';
import DictTag from '@/components/custom/dict-tag.vue';
import SvgIcon from '@/components/custom/svg-icon.vue';
import type { OperLogVo } from '@/service/types/log';
import { useBoolean } from '~/packages/hooks/src';
import PieChart from './components/pie-chart.vue';
import BarChart from './components/line-chart.vue';
import ErrorStack from './components/error-stack.vue';
const { sys_oper_type } = toRefs<any>(useDict('sys_normal_disable', 'sys_oper_type'));
const currentId = ref<number | null | ''>('');
const { bool: visible, setTrue: openVisible } = useBoolean();
const appStore = useAppStore();
const message = useMessage();
const dialog = useDialog();
const handleShowErrorStack = (id: number) => {
  currentId.value = id;
  openVisible();
};

const options = ref([
  {
    label: '保留近1个月',
    key: '0'
  },
  {
    label: '保留近三个月',
    key: '1'
  },
  {
    label: '保留近一年',
    key: '2'
  },
  {
    label: '保留1万条数据',
    key: '3'
  },
  {
    label: '清空所有',
    key: '4'
  }
]);
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams } = useTable({
  apiFn: getPageList,
  showTotal: true,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    status: 0
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'title',
      title: '系统模块',
      align: 'center'
    },
    {
      key: 'operName',
      title: '操作人员',
      align: 'center'
    },
    {
      key: 'operatorType',
      title: '操作类别',
      align: 'center',
      render: (row: OperLogVo) => {
        return <DictTag type="tag" value={row.operatorType} dicts={sys_oper_type.value} />;
      }
    },
    {
      key: 'deptName',
      title: '操作部门',
      align: 'center'
    },
    {
      key: 'operIp',
      title: 'IP地址',
      align: 'center'
    },
    {
      key: 'operLocation',
      title: '操作地点',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'operTime',
      title: '操作日期',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'costTime',
      title: '耗时',
      render: (row: OperLogVo) => {
        return <div>{row.costTime}ms</div>;
      }
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      fixed: 'right',
      render: (row: OperLogVo) => {
        return (
          <>
            {row?.status === 1 && (
              <NTooltip trigger="hover">
                {{
                  trigger: () => (
                    <NButton
                      tag="a"
                      type="primary"
                      text
                      size="small"
                      onClick={() => handleShowErrorStack(row.operId as number)}
                    >
                      {{
                        icon: () => <SvgIcon icon="heroicons-solid:magnifying-glass" />
                      }}
                    </NButton>
                  ),
                  default: () => '查看错误堆栈日志'
                }}
              </NTooltip>
            )}
          </>
        );
      }
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

const handleTabChange = (value: number) => {
  // console.log(value);
  searchParams.status = value;
  getData();
};
const handleClean = (key: string | number) => {
  console.log(key);
  // clean(key);
  dialog.warning({
    title: '警告',
    content: '你确定执行当前操作吗！',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const loadingExample = message.loading('正在处理，请稍等');
      const { error, data } = await clean(key);
      if (!error) {
        message.success(data.msg);
      }
      loadingExample.destroy();
      getData();
    },
    onNegativeClick: () => {
      message.info('已经取消删除');
    }
  });
};
</script>

<template>
  <div class="h-100% min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NGrid y-gap="12" x-gap="12" responsive="screen" item-responsive>
      <NGi span="24 s:24 m:16">
        <BarChart />
      </NGi>
      <NGi span="24 s:24 m:8">
        <PieChart />
      </NGi>
      <NGi span="24 s:24 m:24">
        <div class="h-100% min-h-430px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
          <NCard :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
            <template #header>
              <NTabs type="bar" :on-update:value="handleTabChange">
                <NTab name="0">操作成功</NTab>
                <NTab name="1">操作失败</NTab>
              </NTabs>
            </template>
            <template #header-extra>
              <TableHeaderOperation
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                @refresh="getData"
              >
                <template #default>
                  <NDropdown :options="options" @select="handleClean">
                    <NButton size="small" ghost type="error">
                      <div class="flex flex-row flex-gap-2">
                        <div>清理日志</div>
                        <SvgIcon icon="solar:alt-arrow-down-linear" />
                      </div>
                    </NButton>
                  </NDropdown>
                </template>
              </TableHeaderOperation>
            </template>
            <NDataTable
              v-model:checked-row-keys="checkedRowKeys"
              :columns="columns"
              :data="data"
              size="small"
              :flex-height="!appStore.isMobile"
              :scroll-x="962"
              :loading="loading"
              remote
              :row-key="row => row.operId"
              :pagination="mobilePagination"
              class="sm:h-full"
            >
              <template #empty>
                <Empty />
              </template>
            </NDataTable>
          </NCard>
        </div>
      </NGi>
    </NGrid>
    <ErrorStack v-model:visible="visible" :current-id="currentId" />
  </div>
</template>

<style lang="scss" scoped></style>
